package com.mapmymotion;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jwebsocket.kit.WebSocketException;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;


public class AppSettings extends PreferenceActivity implements OnSharedPreferenceChangeListener {
        private static final String UNIT_STRING = "MeasureUnit";
        //private  String MY_PREFS;// = "SpeedDemo_20100707";
		private static final String login = "login_settings";
		private static final String uom = "uom";
		private static final String notificationInterval = "notification_interval";
		private static final String notificationDistanceInterval = "notificationdistance_interval";			
		private static final String notifications = "notifications";
		private static final String autostart = "autostart";
		private static final String autostop = "autostop";		
		private static final String currentspeed = "current_speed";
		private static final String averagespeed = "avg_speed";		
		private static final String avgpace = "avg_pace";
		private static final String duration = "duration";
		private static final String distance = "distance";
		private static final String updates = "perform_updates";
		private static final String updatesinterval = "updates_interval";
		private static final String currentspeedcue = "current_speed_cue";
		private static final String averagespeedcue = "avg_speed_cue";		
		private static final String avgpacecue = "avg_pace_cue";
		private static final String durationcue = "duration_cue";
		private static final String distancecue = "distance_cue";
		private static final String minpace = "minpace";
		private static final String intervals = "interval";
		private static final String activitytype = "activitytype";
		private static final String login_memberid = "login_memberid";
		
		public static int getmemberid(String email){
			int myid = 0;
			
				//String email = AppSettings.login;
				if (email==null){return myid;}
				// If member id is set no need to login again
				//if (getMemberid(mainActivity.getContext()) > 0){return getMemberid(mainActivity.getContext());}
				//ArrayAdapter<String> activities = null;
				// the year data to send
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				
				nameValuePairs.add(new BasicNameValuePair("email", email));
				InputStream is = null;
				//nameValuePairs.add(new BasicNameValuePair("type", "CYC"));
				// http post
				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(
							"http://mapmymotion.com/getmemberid.php");
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					HttpResponse response = httpclient.execute(httppost);

					HttpEntity entity = response.getEntity();
					is = entity.getContent();

				} catch (Exception e) {

					Log.e("log_tag", "Error in http connection " + e.toString());
				}

				String result = null;
				// convert response to string
				try {
					
					BufferedReader reader = new BufferedReader(new InputStreamReader(
							is, "iso-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();

					result = sb.toString();
				} catch (Exception e) {

					Log.e("log_tag", "Error converting result " + e.toString());
				}
				// parse json data
				try {
					JSONArray jArray = new JSONArray(result);
					JSONObject json_data;
					json_data =jArray.getJSONObject(0);
					myid = json_data.getInt("memberid");
					//setMemberid(mainActivity.getContext(),myid);
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString());
				}
				return myid;		
			}
			
		public static int newUser(String email,String p1,String p2,String fname,String lname){
			int myid = 0;
			
				//If any value is null return 0
				if (email==null || p1==null || p2==null || fname==null || lname==null){return myid;}
				/*String masterpassword="fe1847e7a90065d68155f78280ed7237";
				String masterpassword="mapmymotion";
				try {
					p1 = Crypto.encrypt(masterpassword, p1);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}*/
				// Set up the value pairs
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				
				nameValuePairs.add(new BasicNameValuePair("email", email));
				nameValuePairs.add(new BasicNameValuePair("p1", p1));
				nameValuePairs.add(new BasicNameValuePair("p2", p2));
				nameValuePairs.add(new BasicNameValuePair("fname", fname));
				nameValuePairs.add(new BasicNameValuePair("lname", lname));				
				InputStream is = null;

				// http post
				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(
							"http://mapmymotion.com/newmember.php");
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					HttpResponse response = httpclient.execute(httppost);

					HttpEntity entity = response.getEntity();
					is = entity.getContent();

				} catch (Exception e) {

					Log.e("log_tag", "Error in http connection " + e.toString());
				}

				String result = null;
				// convert response to string
				try {
					
					BufferedReader reader = new BufferedReader(new InputStreamReader(
							is, "iso-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();

					result = sb.toString();
				} catch (Exception e) {

					Log.e("log_tag", "Error converting result " + e.toString());
				}
				// parse json data
				try {
					JSONArray jArray = new JSONArray(result);
					JSONObject json_data;
					json_data =jArray.getJSONObject(0);
					myid = json_data.getInt("memberid");
					setMemberid(mainActivity.getContext(),Integer.toString(myid));
					setEmailAddress(mainActivity.getContext(),email);					
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString());
				}
				return myid;		
			}

		public static int updateFriendStatus(String memberid,String friendsid,String trantype,String email,String fname,String lname){
			int myid = 0;
			
				//If any value is null return -1
				if (friendsid==null || memberid==null){return -1;}

				// Set up the value pairs
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				
				nameValuePairs.add(new BasicNameValuePair("memberid", memberid));
				nameValuePairs.add(new BasicNameValuePair("friendsid", friendsid));
				nameValuePairs.add(new BasicNameValuePair("type", trantype));
				nameValuePairs.add(new BasicNameValuePair("email", email));
				nameValuePairs.add(new BasicNameValuePair("fname", fname));
				nameValuePairs.add(new BasicNameValuePair("lname", lname));
				InputStream is = null;

				// http post
				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(
							"http://mapmymotion.com/updategroupmember.php");
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					HttpResponse response = httpclient.execute(httppost);

					HttpEntity entity = response.getEntity();
					is = entity.getContent();

				} catch (Exception e) {

					Log.e("log_tag", "Error in http connection " + e.toString());
				}

				String result = null;
				// convert response to string
				try {
					
					BufferedReader reader = new BufferedReader(new InputStreamReader(
							is, "iso-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();

					result = sb.toString();
				} catch (Exception e) {

					Log.e("log_tag", "Error converting result " + e.toString());
				}
				// parse json data
				try {
					JSONArray jArray = new JSONArray(result);
					JSONObject json_data;
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString());
				}
				return myid;		
			}

		

		public static String getEmailAddress(Context context){
            return getString(context,AppSettings.login);       
		}
		
   		public static String getActivityType(Context context){
                return getString(context,AppSettings.activitytype);          
        }
   		
        public static int getUOM(Context context){
            return Integer.parseInt(getString(context,AppSettings.uom));               
        }
 
        public static int getMinPace(Context context){
            return Integer.parseInt(getString(context,AppSettings.minpace));       
        
        }        

        public static int getAutoStartInterval(Context context){
            return Integer.parseInt(getString(context,AppSettings.autostart));       
        
        }
        public static int getAutoStopInterval(Context context){
            return Integer.parseInt(getString(context,AppSettings.autostop));       
        
        }        

        public static boolean getCurrentSpeedCue(Context context){
            return getBoolean(context,AppSettings.currentspeedcue);       
        }        

        public static boolean getAverageSpeedCue(Context context){
            return getBoolean(context,AppSettings.averagespeedcue);       
        }        
        public static boolean getPaceCue(Context context){
            return getBoolean(context,AppSettings.avgpacecue);       
        }        
        public static boolean getDurationCue(Context context){
            return getBoolean(context,AppSettings.durationcue);       
        }        
        public static boolean getDistanceCue(Context context){
    		return getBoolean(context,AppSettings.distancecue);       
        }        
                       
        public static boolean getCurrentSpeedSetting(Context context){
            return getBoolean(context,AppSettings.currentspeed);       
        }        

        public static boolean getAverageSpeedSetting(Context context){
            return getBoolean(context,AppSettings.averagespeed);       
        }        
        public static boolean getPaceSetting(Context context){
            return getBoolean(context,AppSettings.avgpace);       
        }        
        public static boolean getDurationSetting(Context context){
            return getBoolean(context,AppSettings.duration);       
        }        
        public static boolean getDistanceSetting(Context context){
    		return getBoolean(context,AppSettings.distance);       
        }        
        public static boolean getIntervalSetting(Context context){
    		return getBoolean(context,AppSettings.intervals);       
        }        
                
        
        
        public static int getNotificationInterval(Context context){
            return Integer.parseInt(getString(context,AppSettings.notificationInterval));       
        
        }
        public static float getNotificationDistanceInterval(Context context){
            return Float.parseFloat(getString(context,AppSettings.notificationDistanceInterval));       
        
        }
        

        public static boolean getNotificationStatus(Context context){
            return getBoolean(context,AppSettings.notifications);       
        
        }

        public static boolean getUpdateStatus(Context context){
            return getBoolean(context,AppSettings.updates);       
        }

        public static int getUpdateInterval(Context context){
            return Integer.parseInt(getString(context,AppSettings.updatesinterval));       
        }
        
        private static boolean getBoolean(Context context, String tag) {
        	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
			return pref.getBoolean(tag,false);
		}

        private static String getString(Context context, String tag) {
        	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);      	
			return pref.getString(tag,null);
		}
		public static String getMemberid(Context context){
			return getString(context,AppSettings.login_memberid);
        }
        
        public static void setMemberid(Context context,String limit){
                putString(context,AppSettings.login_memberid,limit);
        }

        public static void setEmailAddress(Context context,String limit){
            putString(context,AppSettings.login,limit);
    }
        
        private static int getInt(Context context, String tag) {
        		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
                //SharedPreferences pref = context.getSharedPreferences(PREF_NAME, 0);

                return pref.getInt(tag, 0);
        }
        
        public static void putInt(Context context, String tag, int value) {
                //SharedPreferences pref = context.getSharedPreferences(PREF_NAME, 0);
        		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);        	
                SharedPreferences.Editor editor = pref.edit();

                editor.putInt(tag, value);
                editor.commit();
        }
        public static void putString(Context context, String tag, String value) {
            //SharedPreferences pref = context.getSharedPreferences(PREF_NAME, 0);
    		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);        	
            SharedPreferences.Editor editor = pref.edit();

            editor.putString(tag, value);
            editor.commit();
    }
        
        public static String getHMS(long s){	
			int HH= (int) (s/3600);
        	int MM = (int) ((s-(HH*3600))/60);
        	int SS = (int) (s-(HH*3600)-(MM*60));
        	return String.format("Duration %02d:%02d:%02d", HH,MM,SS);        	        	
        }
        public static String getMS(double m){	
        	int MM = (int) m;
        	int SS = (int) (m%1*60);
        	return String.format("Pace %02d:%02d", MM,SS);        	        	
        }

        public void setDefault(){	
        	PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        	}

        
        @Override
            protected void onCreate(Bundle savedInstanceState) {
        	// This has to go first...do not move
            super.onCreate(savedInstanceState);        	
            	addPreferencesFromResource(R.xml.preferences);

            }
        @Override
        public void onRestoreInstanceState(Bundle savedInstanceState) {
          super.onRestoreInstanceState(savedInstanceState);
          // Restore UI state from the savedInstanceState.
          // This bundle has also been passed to onCreate.
          PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
          
        }
        

		public void onSharedPreferenceChanged(SharedPreferences pref,String key) {
		
			//pref = getPreferences(mainActivity.getContext());
			//SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
			if (key.equals("login_settings")){
				//setMemberid(mainActivity.getContext(),Integer.toString(getmemberid(getEmailAddress(mainActivity.getContext()))));
				try {
					JWC.getMemberId(getEmailAddress(mainActivity.getContext()));
					
				} catch (WebSocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			SharedPreferences.Editor editor = pref.edit();
			editor.commit();
			onContentChanged();
			// TODO Auto-generated method stub
		}
		@Override
		protected void onResume() {
		    super.onResume();
		    // Set up a listener whenever a key changes
		    getPreferenceScreen().getSharedPreferences()
		            .registerOnSharedPreferenceChangeListener(this);
		}

		@Override
		protected void onPause() {
			/*SharedPreferences pref = getSharedPreferences("MY_PREFS", 0);
			SharedPreferences.Editor editor = pref.edit();
			editor.commit();*/
		    super.onPause();
		    // Unregister the listener whenever a key changes
		    getPreferenceScreen().getSharedPreferences()
		          .unregisterOnSharedPreferenceChangeListener(this);

		}
		


}
